package com.ddwl.message.repository.impl;

import com.ddwl.common.constant.BaseEnum;
import com.ddwl.message.model.Sos;
import com.ddwl.message.repository.SosRepositoryAdvance;
import com.ddwl.schema.bo.base.LocationBo;
import com.ddwl.schema.bo.base.PageBo;
import com.ddwl.schema.bo.message.SosPageBo;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

/**
 * @author Fu Zhaohui
 * @version 1.0.0
 * @date 2019/8/29 19:41
 */
public class SosRepositoryImpl implements SosRepositoryAdvance {

    @Autowired
    private MongoTemplate template;

    @Override
    public Page<Sos> findPage(PageBo<SosPageBo> pageBo) {
        Criteria criteria = Criteria.where("dflag").is(BaseEnum.DflagEnum.NOT_DELETE.getCode());
        Pageable pageable = PageRequest.of(pageBo.getPage() - 1, pageBo.getPageSize(), Sort.Direction.DESC, "gmtCreated");
        Query query = Query.query(criteria);
        return new PageImpl<>(template.find(query.with(pageable), Sos.class), pageable, template.count(query, Sos.class));
    }

    @Override
    public void delete(String id) {
        template.updateFirst(Query.query(Criteria.where("_id").is(new ObjectId(id))), Update.update("dflag", true), Sos.class);
    }

    @Override
    public List<Sos> findNear(LocationBo loc) {
        Point point = new Point(loc.getLat(), loc.getLng());
        Criteria criteria = Criteria.where("loc").near(point).maxDistance(20).and("dflag").is(BaseEnum.DflagEnum.NOT_DELETE.getCode());
        return template.find(Query.query(criteria), Sos.class);
    }
}
